package com.lagou.client;

import com.lagou.pojo.RpcRequest;
import com.lagou.utils.JSONSerializer;
import com.lagou.utils.RequestMetrics;
import com.lagou.utils.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class RpcClient {

    public final String host;
    public final Integer port;
    public RpcConsumer consumer;

    private EventLoopGroup group;
    public UserClientHandler handler;
    public Channel channel;

    public RpcClient(String host, int port,RpcConsumer consumer){
        this.host = host;
        this.port = port;
        this.consumer = consumer;
    }

    public void connect() throws InterruptedException {
        this.group = new NioEventLoopGroup();
        handler = new UserClientHandler(this);

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(handler);
                    }
                });


        this.channel = b.connect(host, port).sync().channel();
        if(!isValidate()){

            return;
        }
        System.out.println("客户端已启动成功,port:{"+port+"}，开始登录服务端");
    }


    public boolean isValidate() {
        if(this.channel !=null){
            return this.channel.isActive();
        }
        return false;
    }

    /**
     * 移除服务端
     */
    public void removeService(){
        if(consumer.clientMap.containsKey(host+":"+port)){
            RequestMetrics.removeNode(host,port);
            consumer.clientMap.remove(host+":"+port);
            System.out.println("移除"+host+":"+port);
        }
    }

    public void setStart(String requestId){
        RequestMetrics.put(host,port,requestId);
    }
}
